package com.starhub.domain.ai.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.starhub.application.model.biz.VectorModelFactory;
import com.starhub.domain.ai.service.IVectorService;

import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.output.Response;

import java.util.ArrayList;
import java.util.List;

@Service
public class VectorServiceImpl implements IVectorService {
    private static final Logger log = LoggerFactory.getLogger(VectorServiceImpl.class);

    @Autowired
    VectorModelFactory vectorModelFactory;

    @Override
    public String search(String vectorStoreId, String query) {
        return null;
    }

    /*@Autowired
    private EmbeddingModel embeddingModel;*/

    @Override
    public float[] textToVector(String text) {
        try {
            EmbeddingModel embeddingModel = vectorModelFactory.getVectorModel("baidu");
            Response<Embedding> response = embeddingModel.embed(text);
            float[] vector = response.content().vector();
            return vector;
        } catch (Exception e) {
            log.error("文本转向量失败: {}", text, e);
            throw new RuntimeException("文本转向量失败: " + e.getMessage());
        }
    }

    @Override
    public List<float[]> textsToVectors(List<String> texts) {
        List<float[]> vectors = new ArrayList<>();
        for (String text : texts) {
            vectors.add(textToVector(text));
        }
        return vectors;
    }

    @Override
    public float calculateSimilarity(float[] vector1, float[] vector2) {
        if (vector1.length != vector2.length) {
            throw new IllegalArgumentException("向量维度不一致");
        }

        float dotProduct = 0;
        float norm1 = 0;
        float norm2 = 0;

        for (int i = 0; i < vector1.length; i++) {
            dotProduct += vector1[i] * vector2[i];
            norm1 += vector1[i] * vector1[i];
            norm2 += vector2[i] * vector2[i];
        }

        norm1 = (float) Math.sqrt(norm1);
        norm2 = (float) Math.sqrt(norm2);

        if (norm1 == 0 || norm2 == 0) {
            return 0;
        }

        return dotProduct / (norm1 * norm2);
    }

    @Override
    public List<String> searchSimilarTexts(String query, int topK) {
        // TODO: 实现向量库搜索
        throw new UnsupportedOperationException("向量库搜索功能尚未实现");
    }
} 